﻿using System;
using System.Collections.Generic;
using System.Xml.Linq;

namespace FluentlyXml.Core.Serialization
{
	internal class SerializationContext : ISerializationContext
	{
		private readonly FluentSerializer _serializer;
		private readonly Stack<object> _cycleDetector;

		public SerializationContext(FluentSerializer fluentSerializer)
		{
			_serializer = fluentSerializer;
			_cycleDetector = new Stack<object>();
		}

		public XElement Serialize(Type type, object obj)
		{
			if (_cycleDetector.Contains(obj))
			{
				throw new CycleDetectedException(type, obj);
			}

			_cycleDetector.Push(obj);
			var element = _serializer.SerializeInternal(type, obj, this);
			_cycleDetector.Pop();

			return element;
		}
	}
}